#include <REG52.H>

sbit XPT2046_CS   = P3 ^ 5;
sbit XPT2046_DCLK = P3 ^ 6;
sbit XPT2046_DIN  = P3 ^ 4;
sbit XPT2046_DOUT = P3 ^ 7;

/**
 * @brief XPT2046专用延时，约200us
 */
void XPT2046_Delay(void) //@11.0592MHz
{
    unsigned char data i;
    i = 89;
    while (--i);
}

/**
 * @brief 读取XPT2046的AD值
 * @param cmd 读取的AD值类型
 * @return 读取的AD值
 */
unsigned int XPT2046_ReadAD(unsigned char cmd)
{
    char i;
    unsigned int ad = 0;

    XPT2046_DCLK = 0;
    XPT2046_CS   = 0;

    for (i = 7; i >= 0; i--) {
        XPT2046_DIN  = (cmd >> i) & 0x01;
        XPT2046_DCLK = 1;
        XPT2046_DCLK = 0;
    }
    //  busy
    for (i = 0; i < (cmd & 0x08 ? 8 : 12); i++) {
        ad <<= 1;
        XPT2046_DCLK = 1;
        XPT2046_DCLK = 0;
        XPT2046_Delay();
        ad |= XPT2046_DOUT;
    }
    XPT2046_CS = 1;
    return ad;
}